﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace 文件浏览 {
    public partial class WebForm1 : System.Web.UI.Page {
        protected void Page_Load (object sender, EventArgs e) {
            if(!IsPostBack)
            {
                //循环遍历每-一个磁盘驱动器
                foreach (DriveInfo drive in DriveInfo.GetDrives())
                {
                    TreeNode n = new TreeNode(); //定 义树状菜单的父节点
                    n.Value = drive.Name;
                    if (drive.IsReady) //判断如果驱动器已经准备完毕
                    {
                        n.Text = drive.Name + "(可用空间为:" + drive.AvailableFreeSpace + ")";
                        //递归调用自定义的方法，遍历当前的驱动器目录
                        AddDirectories(drive.RootDirectory, n);
                        this.TreeView1.Nodes.Add(n); //将节点添加到树状菜单
                    }
                    else
                    {
                        n.Text = drive.Name + "-(磁盘尚未准备好!)";
                    }
                    this.TreeView1.CollapseAll(); //将树状菜单收拢
                }
            }


        }

        private void AddDirectories (DirectoryInfo d, TreeNode parent) {
            //获得驱动器下目录集合
            DirectoryInfo[] directory = d.GetDirectories ();
            try {
                foreach (DirectoryInfo di in directory) {
                    TreeNode node = new TreeNode ();
                    node.Value = di.Name;
                    node.Text = di.Name;
                    parent.ChildNodes.Add (node);
                    foreach (DirectoryInfo mini_di in di.GetDirectories())
                    {
                        if (mini_di.Exists)
                        {
                            AddDirectories(mini_di,node);
                        }
                    }
                }
            } catch (System.UnauthorizedAccessException e) {
                parent.Text += "(访问被拒绝)";
            }
            catch (IOException el)
            {
                    parent .Text ="(未知的错误: " + el.Message + ")";
            }
        }

        //定义树状菜单的子节点，并将目录的名称添加其上

    }
}